<?php

namespace App\Http\Controllers\OpenShop\FeishuMini;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Http\Controllers\BaseController;
use App\Models\Common\ConfigModel;
use App\Service\BaseService;
use App\Service\OpenShop\FeishuMini\ProgrammingService;
use App\Service\OpenShop\FeishuMini\SandTableService;
use App\Service\OpenShop\SiteLocation\AuthService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProgrammingController extends BaseController
{

    public function sift(Request $request)
    {
        $this->validate($request, [
            'city' => 'string'
        ]);
        $city = $request->get('city', '');
        // 不同路由获取
        $action     = request()->route()->getAction();
        $middleware = attributeGet($action, "middleware", []);
        $isKms      = false;
        if (in_array('kmsAuth:kmsApi', $middleware)) {
            $isKms = true;
        }
        return $this->success(ProgrammingService::sift($city, $isKms));
    }


    public function hotCity(Request $request)
    {
        return $this->success(ProgrammingService::hotCity());
    }

    public function cityListByPower(Request $request)
    {
        return $this->success(ProgrammingService::cityListByPower($request->haveCity));
    }

    public function getCityByLatLng(Request $request)
    {
        $request->validate([
            'lng' => 'required',
            'lat' => 'required',
        ]);
        $lng = $request->get('lng');
        $lat = $request->get('lat');
        return $this->success(ProgrammingService::getCityByLatLng($request->haveCity, $lat, $lng));
    }

    public function list(Request $request)
    {
        $request->validate([
            'type'         => 'int|required',
            'city'         => 'string',
            'sort'         => 'string',
            'settleStatus' => 'string',
            'grade'        => 'string',
            'chosen'       => 'string',
            'name'         => 'string',
        ]);
        //类型
        $type = $request->get('type');
        //子类型
        $subType = (int)$request->get('subType', ProgrammingEnum::SUB_TYPE_DEFAULT);
        //省
        $provinceCode = (int)$request->get('provinceCode', 0);
        if ($provinceCode == 1) {//前端全部传值需删除
            $provinceCode = 0;
        }
        //城市
        $city     = $request->get('city', '');
        $cityCode = (int)$request->get('cityCode', 0);
        //区域
        $district     = $request->get('district', '');
        $districtCode = (int)$request->get('districtCode', 0);
        //排序
        $sort = $request->get('sort', '');
        //状态
        $status = $request->get('status', '');
        //可开潜力
        $openScore = $request->get('openScore', '');
        //入驻状态
        $settleStatus = $request->get('settleStatus', '');
        //等级
        $grade = $request->get('grade', '');
        //入选表单
        $chosen = $request->get('chosen', '');
        //网规名称
        $name = $request->get('name', '');
        //经度
        $lng = $request->get('lng');
        //纬度
        $lat      = $request->get('lat');
        $pageNum  = (int)$request->get('pageNum', 1);
        $pageSize = (int)$request->get('pageSize', 10);
        $isOwn    = (bool)$request->get('isOwn', false);//true 只看自己的
        $searchId = (int)$request->get('id', 0);// 列表查询单个数据

        // 不同路由获取用户id
        $action     = request()->route()->getAction();
        $middleware = attributeGet($action, "middleware", []);
        $authUser   = [];
        $isKms      = false;
        if (in_array('kmsAuth:kmsApi', $middleware)) {
            $authUser['userId'] = request()->user()->rmsUserId;
            $isKms              = true;
        } else {
            $authUser = AuthService::getRmsUserInfo($request);
            if (!$city) {
                BaseService::throwErr('城市必传');
            }
        }
        return $this->success(
            ProgrammingService::list(
                $type, $subType, $city, $district, $lng, $lat, $pageNum, $pageSize,
                $sort, $status, $openScore, $settleStatus, $grade, $chosen, $name, [], [], $authUser, $isKms, $isOwn,
                $provinceCode, $cityCode, $districtCode, $searchId
            )
        );
    }


    public function detail(Request $request)
    {
        $request->validate([
            'type' => 'int|required',
            'id'   => 'int|required|min:1',
        ]);
        // 不同路由获取用户id
        $action     = request()->route()->getAction();
        $middleware = attributeGet($action, "middleware", []);
        if (in_array('kmsAuth:kmsApi', $middleware)) {
            $rmsUserId = request()->user()->rmsUserId;
        } else {
            $authUser  = AuthService::getRmsUserInfo($request);
            $rmsUserId = $authUser['userId'] ?? 0;
        }
        $type      = $request->get('type');
        $id        = $request->get('id');
        return $this->success(ProgrammingService::detail($type, $id, $rmsUserId));
    }

    public function getNearbyDot(Request $request)
    {
        $request->validate([
            'lng' => 'required',
            'lat' => 'required',
        ]);

        $lng = $request->get('lng');
        $lat = $request->get('lat');
        return $this->success(ProgrammingService::getNearbyDot($lng, $lat));
    }

    public function getWgDotByCity(Request $request)
    {
        $request->validate([
            'city'         => 'string|required',
            'type'         => 'int|required',
            'status'       => 'string',
            'settleStatus' => 'string',
            'grade'        => 'string',
            'chosen'       => 'string',
            'name'         => 'string',
            'district'     => 'string',
        ]);

        //类型
        $type = $request->get('type');
        //城市
        $city = $request->get('city');
        //区域
        $district = $request->get('district', '');
        //状态
        $status = $request->get('status', '');
        //可开潜力
        $openScore = $request->get('openScore', '');
        //入驻状态
        $settleStatus = $request->get('settleStatus', '');
        //等级
        $grade = $request->get('grade', '');
        //入选表单
        $chosen = $request->get('chosen', '');
        //网规名称
        $name = $request->get('name', '');
        return $this->success(ProgrammingService::getWgDotByCity($type, $city, $district, $status, $openScore, $settleStatus, $grade, $chosen, $name));
    }


    public function dotEvaluate(Request $request)
    {
        $request->validate([
            'id'           => 'int|required',
            'type'         => 'required',
            'content'      => 'string',
            'evaluateId'   => 'int',
            'evaluateTime' => 'string',  //评估时间
        ]);
        $id                 = $request->post('id');
        $evaluateId         = $request->post('evaluateId', 0);
        $type               = $request->post('type');
        $openPotential      = $request->post('openPotential');//可开潜力
        $content            = $request->post('content');
        $evaluateTime       = $request->post('evaluateTime');
        $flowScore          = $request->post('flowOfPeopleScores');                //人流量
        $flowFile           = $request->post('wangguiFlowOfPeople');               //人流量文件
        $businessFile       = (array)$request->post('wangguiBusinessDistribution');//业态分布文件
        $customerGroupType  = (array)$request->post('customerGroupType');          //客群类型
        $passengerFlowDrive = (array)$request->post('passengerFlowDrive');                //客流驱动
        $canOpenArea        = $request->post('openDistrictList');                  //可开区域
        $overallMovingLine  = (array)$request->post('wangguiOverallMovingLine');   //整体动线
        $takeawayEvaluation = (array)$request->post('wangguiTakeawayEvaluation');  //外卖预估
        $floorGuidance      = (array)$request->post('wangguiFloorGuidance');       //楼层指引
        $authUser    = AuthService::getRmsUserInfo($request);
        $rmsUserId   = $authUser['userId'] ?? 0;
        $rmsUserName = $authUser["username"] ?? "";
        if (is_numeric($type)) {
            //网规评估
            ProgrammingService::dotEvaluate($id, $type, $openPotential, $content, $flowScore, $flowFile, $businessFile, $customerGroupType, $passengerFlowDrive, $canOpenArea, $overallMovingLine, $takeawayEvaluation, $floorGuidance, $rmsUserName, $rmsUserId, $evaluateId, $evaluateTime);
        } else {
            //沙盘评估
            SandTableService::dotEvaluate($id, $type, $openPotential, $content, $flowScore, $flowFile, $businessFile, $customerGroupType, $passengerFlowDrive, $canOpenArea, $overallMovingLine, $takeawayEvaluation, $floorGuidance, $rmsUserName, $rmsUserId, $evaluateId, $evaluateTime);
        }
        return $this->success();
    }


    /**
     * @throws GuzzleException
     */
    public function evaluateDetail(Request $request): JsonResponse
    {
        $request->validate([
            'id' => 'required|int',
        ]);
        $authUser  = AuthService::getRmsUserInfo($request);
        $rmsUserId = $authUser['userId'] ?? 0;
        return $this->success(ProgrammingService::evaluateDetail($request->id, $rmsUserId));
    }

    public function evaluateUpdate(Request $request, $id) {}

    public function capacity(Request $request)
    {
        $request->validate([
            'type'         => 'int|required',
            'city'         => 'string',
            'sort'         => 'string',
            'status'       => 'string',
            'settleStatus' => 'string',
            'grade'        => 'string',
            'chosen'       => 'string',
            'name'         => 'string',
        ]);
        //类型
        $type = $request->get('type');
        //省
        $provinceCode = (int)$request->get('provinceCode', 0);
        if ($provinceCode == 1) {//前端全部传值需删除
            $provinceCode = 0;
        }
        //城市
        $city     = $request->get('city', '');
        $cityCode = (int)$request->get('cityCode', 0);
        //区域
        $districtCode = (int)$request->get('districtCode', 0);
        //排序
        $sort = $request->get('sort', '');
        //状态
        $status = $request->get('status', '');
        //入驻状态
        $settleStatus = $request->get('settleStatus', '');
        //等级
        $grade = $request->get('grade', '');
        //入选表单
        $chosen = $request->get('chosen', '');
        //网规名称
        $name = $request->get('name', '');

        $isOwn = (bool)$request->get('isOwn', false);//true 只看自己的

        // 不同路由获取用户id
        $action     = request()->route()->getAction();
        $middleware = attributeGet($action, "middleware", []);
        $isKms      = false;
        $authUser   = [];
        if (in_array('kmsAuth:kmsApi', $middleware)) {
            $isKms              = true;
            $authUser['userId'] = request()->user()->rmsUserId;
        } else {
            if (!$city) {
                BaseService::throwErr('城市必传');
            }
        }

        return $this->success(
            ProgrammingService::capacity(
                $type, $city, $sort, $status, $settleStatus, $grade, $chosen, $name, $isKms, $isOwn, $authUser, $provinceCode, $cityCode, $districtCode
            )
        );
    }

    public function browsingHistory(Request $request)
    {
        $authUser  = AuthService::getRmsUserInfo($request);
        $rmsUserId = $authUser['userId'] ?? 0;
        $pageNum   = (int)$request->get('pageNum', 1);
        $pageSize  = (int)$request->get('pageSize', 10);
        $name      = $request->get('name', '');
        return $this->success(ProgrammingService::browsingHistory($rmsUserId, $pageNum, $pageSize, $name));
    }

    public function evaluateHistory(Request $request)
    {
        $authUser  = AuthService::getRmsUserInfo($request);
        $rmsUserId = $authUser['userId'] ?? 0;
        $pageNum   = (int)$request->get('pageNum', 1);
        $pageSize  = (int)$request->get('pageSize', 10);
        $name      = $request->get('name', '');
        return $this->success(ProgrammingService::evaluateHistory($rmsUserId, $pageNum, $pageSize, $name));
    }


    public function importStreet(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'url'  => 'required|string'
        ]);

        $name = $request->post('name');
        $url  = $request->post('url');
        ini_set('max_execution_time', '600');
        ignore_user_abort(true);
        ProgrammingService::importStreet($name, $url);
        return $this->success();
    }


}
